package com.sunye.rabbit_mq_delay;


import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component
@Slf4j
public class OrderListener {

    @RabbitListener(queues = {MQCont.QUEUE_ORDER_CANCEL})
    public void cancelOrder(Channel channel, Message message){
        try {
            String msg = new String(message.getBody());
            log.info("当前时间：{},延时队列收到消息：{}", new Date().toString(), msg);
            //TODO 处理业务
            //手动签收
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
           if(message.getMessageProperties().isRedelivered()){
               //如果是重新交付的
               try {
                   log.error("失败了------------------------------");
               }catch (Exception exception){
                   exception.printStackTrace();
               }finally {
                   try {
                       //如果第二次又失败  将消息丢弃
                       channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                   } catch (Exception exc) {
                       exc.printStackTrace();
                   }
               }
           }else{
               try {
                   log.error("失败了------------------------------");
                   //如果第一次失败 再次尝试执行任务
                   channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
               } catch (IOException ex) {
                   ex.printStackTrace();
               }
           }
            e.printStackTrace();
        }

    }

}
